package com.mrjy.integral.bo;

import com.mrjy.common.entity.HappinessInfo;
import com.mrjy.common.entity.SignInInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.dao.ISignInInfoDao;
import com.mrjy.integral.dto.HappinessInfoNotCollectDTO;
import com.mrjy.integral.util.HappinessInfoUtil;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.video.dao.IUserVideoRelDao;
import com.mrjy.video.dao.IVideoInfoDao;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("HappinessInfoBo")
public class HappinessInfoBo implements IHappinessInfoBo{
	
	@Resource
	private IHappinessInfoDao happinessInfoDao;
	@Resource
	private ISignInInfoDao signInInfoDao;
	@Resource
	private IUserVideoRelDao userVideoRelDao;
	@Resource
	private IVideoInfoDao videoInfoDao;
	@Resource
	private IUserInfoDao userInfoDao ;

	@Override
	public Object txInsert(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		info.setCreateTime(new Timestamp(System.currentTimeMillis()));
		info.setDisableFlag(0);
		
		int count = happinessInfoDao.insert(info);
		if(count == 1){
			map.put("err_code", 0);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "插入失败")	;
		}
		return map ;
		
	}
	@Override
	public Object queryById(int id) {
		Map<String, Object> map = new HashMap<String,Object>();
		HappinessInfo info = happinessInfoDao.queryById(id);
		if(info != null){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", info);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
		}
		return map;
	}
	@Override
	public Object txUpdateById(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		int count = happinessInfoDao.updateById(info);
		if(count == 1){
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败")	;
		}
		return map ;
	}
	@Override
	public int deleteByIds(int[] ids) {
		try{
			return happinessInfoDao.deleteByIds(ids);
		}catch(DataAccessException  e){
			return 0;
		}
	}
	@Override
	public int updateDisableFlag(HappinessInfo info) {
		return happinessInfoDao.updateDisableFlag(info);
	}
	
	@Override
	public Object queryIndexInfoByUserId(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		//1.查询当天未收取的幸福值（爱值）
		List<HappinessInfoNotCollectDTO> list = happinessInfoDao.queryNotCollectListByUserId(info.getUserId());
		if(list != null && list.size() > 0){
			map.put("love_list", list);
		}else{
			map.put("love_list", null);
		}
		//2.查询所有已经收取的幸福值
		info.setIsCollect("1");
		int total_collected_love = happinessInfoDao.queryToTalLoveByUserIdAndIsCollect(info);
		map.put("total_collected_love", total_collected_love);
		
		//3.坚持天数（连续签到天数）和检测查询当天是否已经签到
		SignInInfo existInfo = signInInfoDao.queryByUserId(info.getUserId());
		if(existInfo == null){//还没签过到
			map.put("conti_days", 0);//连续签到天数
			map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
		}else{
			if(existInfo.getLastModifyTime() != null){
				//先判断现在的时间点是否已经签到
				if(DateUtil.isSameDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
					map.put("conti_days", existInfo.getContinuitySignCount());//连续签到天数
					map.put("is_sign", 1);//是否签到（0：未签; 1:已签）
					map.put("sign_in_score", IntegralUtil.getScoreBySignInDay(existInfo.getContinuitySignCount()>=5?5:existInfo.getContinuitySignCount()));
				}else {
					//判断是否是断签
					if(DateUtil.isBeforDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
						//没断签
						map.put("conti_days", existInfo.getContinuitySignCount());//连续签到天数
						map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
					}else{
						//断签，按未签处理
						map.put("conti_days", 0);//连续签到天数
						map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
					}
				}
			}else{//数据异常，理论上不存在，如果出现按未签处理
				map.put("conti_days", 0);//连续签到天数
				map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
			}
		}
		//4.查询学完的视频数，然后计算出成长树的成长阶段
		int finishedVideoCount = userVideoRelDao.queryTotalFinishedVideoCountByUserId(info.getUserId());
        int minutes = userVideoRelDao.queryTotalSecVideoCountByUserId(info.getUserId()) / 60;
        map.put("finished_video_count", finishedVideoCount);//已学课程数
        map.put("finished_minutes", minutes);//已学课程数
        //查询总视频数
		int totalVideo = videoInfoDao.queryTotalVideo();
		if(totalVideo != 0){
			map.put("tree_type", HappinessInfoUtil.getTreeType(finishedVideoCount, totalVideo));
		}else{
			map.put("tree_type", "A");//如果总视频数为0，则默认为A
		}
		//5.查询心愿
		UserInfo ui = userInfoDao.queryById(info.getUserId());
		if(ui != null){
			map.put("wish", ui.getWish());
            map.put("familyPic", ui.getFamilyPic());
        } else {
            map.put("wish", "");
            map.put("familyPic", "");
        }
        return map;
	}
	@Override
	public Object txCollectLove(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		if(StringUtils.isBlank(info.getTypeId())){
			map.put("err_code", -2);
			map.put("err_msg", "幸福的爱类型id为空");
			return map;
		}
		int row = happinessInfoDao.collectLove(info);
		if(row > 0){
			map.put("err_code", 200);
			map.put("err_msg", "收集幸福的爱成功");
		}else{
			map.put("err_code", 401);
			map.put("err_msg", "收集幸福的爱失败");
		}
		return map;
	}
	@Override
    public Object txMakeWish(Integer userId, String wish, String familyPic) {
        Map<String, Object> map = new HashMap<String, Object>();
        if(userId == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map ;
		}
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(familyPic)) {
            paramMap.put("familyPic", familyPic);
        }
        if (StringUtils.isNotBlank(wish)) {
            paramMap.put("wish", wish);
        }

        Timestamp updateTime = new Timestamp(System.currentTimeMillis());
		paramMap.put("userId", userId);
        paramMap.put("updateTime", updateTime);
        int row = happinessInfoDao.makeWish(paramMap);
        if (row == 1) {
            map.put("err_code", 200);
			map.put("err_msg", "许愿成功");
		}else {
			map.put("err_code", 100);
			map.put("err_msg", "许愿失败");
		}
		return map;
	}
	@Override
	public Object txCollectLoveValue() {
		Map<String , Object> map = new HashMap<String, Object>();
		
		int row = happinessInfoDao.collectLoveTimeTask();
		if(row > 0){
			map.put("err_code", 200);
			map.put("err_msg", "收取幸福的爱成功，共操作了" + row + "条记录");
		}else{
			map.put("err_code", 201);
			map.put("err_msg", "收取幸福的爱成功，共操作了" + row + "条记录");
		}
		
		return map;
	}
	@Override
	public Object queryHappyTreeInfoByUserId(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		//1.查询当天未收取的幸福值（爱值）
		List<HappinessInfoNotCollectDTO> list = happinessInfoDao.queryNotCollectListByUserId(info.getUserId());
		if(list != null && list.size() > 0){
			map.put("love_list", list);
		}else{
			map.put("love_list", null);
		}
		//2.查询所有已经收取的幸福值
		info.setIsCollect("1");
		int total_collected_love = happinessInfoDao.queryToTalLoveByUserIdAndIsCollect(info);
		map.put("total_collected_love", total_collected_love);
		
		//4.查询学完的视频数，然后计算出成长树的成长阶段
		int finishedVideoCount = userVideoRelDao.queryTotalFinishedVideoCountByUserId(info.getUserId());
        //查询总视频数
		int totalVideo = videoInfoDao.queryTotalVideo();
		if(totalVideo != 0){
			map.put("tree_type", HappinessInfoUtil.getTreeType(finishedVideoCount, totalVideo));
		}else{
			map.put("tree_type", "A");//如果总视频数为0，则默认为A
		}
		//5.查询心愿
		UserInfo ui = userInfoDao.queryById(info.getUserId());
		if(ui != null){
			map.put("wish", ui.getWish());
            map.put("familyPic", ui.getFamilyPic());
        } else {
            map.put("wish", "");
            map.put("familyPic", "");
        }
        return map;
	}
	@Override
	public Object queryHappyRoadInfoByUserId(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		//3.坚持天数（连续签到天数）和检测查询当天是否已经签到
		SignInInfo existInfo = signInInfoDao.queryByUserId(info.getUserId());
		if(existInfo == null){//还没签过到
			map.put("conti_days", 0);//连续签到天数
			map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
		}else{
			if(existInfo.getLastModifyTime() != null){
				//先判断现在的时间点是否已经签到
				if(DateUtil.isSameDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
					map.put("conti_days", existInfo.getContinuitySignCount());//连续签到天数
					map.put("is_sign", 1);//是否签到（0：未签; 1:已签）
					map.put("sign_in_score", IntegralUtil.getScoreBySignInDay(existInfo.getContinuitySignCount()>=5?5:existInfo.getContinuitySignCount()));
				}else {
					//判断是否是断签
					if(DateUtil.isBeforDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
						//没断签
						map.put("conti_days", existInfo.getContinuitySignCount());//连续签到天数
						map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
					}else{
						//断签，按未签处理
						map.put("conti_days", 0);//连续签到天数
						map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
					}
				}
			}else{//数据异常，理论上不存在，如果出现按未签处理
				map.put("conti_days", 0);//连续签到天数
				map.put("is_sign", 0);//是否签到（0：未签; 1:已签）
			}
		}
        return map;
	}
	@Override
	public Object queryHappySocureByUserId(HappinessInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		//2.查询所有已经收取的幸福值
		info.setIsCollect("1");
		int total_collected_love = happinessInfoDao.queryToTalLoveByUserIdAndIsCollect(info);
		map.put("total_collected_love", total_collected_love);
        return map;
	}


}
